<template>
  <div class="app-container">
    <div class="user-unit-box">
      <div class="user-unit-box-left">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px; width: 90%" />
        </div>
        <div class="head-container">
          <div class="tree-box">
            <el-tree height="600" :data="treeData" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
          </div>
        </div>
      </div>
      <div class="user-unit-box-right">
        <div class="filter-container">
          <!-- <el-date-picker
            v-model="listQuery.created_at"
            size="small"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            class="filter-item"
            :editable="false"
          /> -->
          <el-input v-model="listQuery.keyWord" size="small" placeholder="请输入关键词" clearable class="filter-item w-200" />
          <!-- <el-button-group class="filter-item"> -->
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="refresh">重置</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <!-- </el-button-group> -->
        </div>
        <el-table v-loading="listLoading" :data="tableData" element-loading-text="Loading" border height="600px"
          class="table-container" highlight-current-row>
          <el-table-column label="序号" width="80" align="center">
            <template slot-scope="scope">
              <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账号" width="150" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.userUid }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户名" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName }}
            </template>
          </el-table-column>
          <el-table-column label="性别" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.userSex == 'male' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column label="所属街道" width="100" align="center" prop="streetTown">
          </el-table-column>
          <el-table-column label="用户类型" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.userType }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="用户角色" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.roles }}
            </template>
          </el-table-column> -->
          <el-table-column label="邮箱" align="center">
            <template slot-scope="scope">
              {{ scope.row.userEmail }}
            </template>
          </el-table-column>
          <el-table-column label="电话" width="130" align="center">
            <template slot-scope="scope">
              {{ scope.row.mobilePhone }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <div class="operate_area">
                <span class="fpjs" @click="editUser(scope)">分配角色</span>
                <span style="margin-left: 5px;" class="fpjs" @click="deleteUser(scope)">删除</span>
                <!-- <img src="@/assets/icon/delete.png" alt="" class="delete" @click="del(scope)" /> -->
                <!-- <img src="@/assets/icon/edit.png" alt="" class="edit" @click="edit(scope)" />
                <img src="@/assets/icon/delete.png" alt="" class="delete" @click="del(scope)" /> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination style="margin-top: 20px" v-show="total > 0" :total="total" :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'modify' ? '修改' : '新增'">
      <el-form ref="dataForm" :model="formData" label-width="120px" label-position="right">
        <el-form-item label="分配角色" class="inputBox">
          <el-select clearable v-model="roles" multiple placeholder="请选择" :popper-append-to-body="false">
            <el-option v-for="item in roleList" :key="item.OBJECTID" :label="item.NAME"
              :value="item.OBJECTID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formData.userUid" placeholder="请输入账号" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="formData.userName" placeholder="请输入用户名" disabled />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.userSex" disabled>
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-input v-model="formData.userType" placeholder="请输入用户类型" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formData.userEmail" placeholder="请输入邮箱" disabled />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formData.mobilePhone" placeholder="请输入电话" disabled />
        </el-form-item>
      </el-form>
      <div class="text-right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>


    <el-dialog :visible.sync="dialogAdd" :title="dialogType === 'modify' ? '修改' : '新增'">
      <el-form ref="dataForm" :rules="rules" :model="formData" label-width="120px" label-position="right">
        <el-form-item label="账号" prop="userUid">
          <el-input v-model="formData.userUid" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input type="password" v-model="formData.password2" placeholder="请输入确认密码" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.userSex">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属街道">
          <el-input v-model="formData.streetTown" placeholder="请输入所属街道" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-input v-model="formData.userType" placeholder="请输入用户类型" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formData.userEmail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formData.mobilePhone" placeholder="请输入电话" />
        </el-form-item>
      </el-form>
      <div class="text-right">
        <el-button type="danger" @click="dialogAdd = false">取消</el-button>
        <el-button type="primary" @click="userAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//import { getList } from '@/api/user'
//import { deepClone } from '@/utils'
import { getUserList, getOrgTreeSelect, getRoles, updateUserRole, addUser, delUser, addUserByOwner } from '@/http/api/myHttp.js'

export default {
  components: {},
  data() {
    return {
      deptName: '',
      deptOptions: [],
      queryParams: {},
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //********************************* */
      formData: {},
      total: 0,
      tableData: [],
      roleList: [],
      roles: [],
      userId: '',
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      listQuery2: {
        pageNo: 1,
        pageSize: 1000
      },
      dialogVisible: false,
      dialogType: 'create',
      loading: false,
      dialogAdd: false,
      rules: {
        userUid: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请输入确认密码', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.fetchData()
    this.getDep()
  },
  methods: {
    add() {
      this.dialogAdd = true
      this.dialogType = '新增'
    },
    userAdd() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.formData.password != this.formData.password2) {
            this.$message.error('两次密码不一致')
            return
          }
          addUserByOwner(this.formData).then(res => {
            if (res.code == 0) {
              this.$message.success('新增用户成功！')
              this.dialogAdd = false
              this.$refs['dataForm'].resetFields();
            }

          })
        }
      })


    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.listQuery.orgCode = data.code
      this.fetchData()
    },
    //********************************************************************** */
    search() {
      this.fetchData()
    },
    refresh() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 10
      }
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      for (let key in this.listQuery) {
        if (!this.listQuery[key]) {
          delete this.listQuery[key]
        }
      }
      getUserList(this.listQuery).then((res) => {
        if (res.code == 0) {
          this.listLoading = false
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    editUser(scope) {
      this.dialogVisible = true
      this.dialogType = 'modify'
      this.formData = JSON.parse(JSON.stringify(scope.row))
      this.userId = scope.row.objectid
      if (scope.row.roles) {
        this.roles = scope.row.roles.split(',') //转数组
      }
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    deleteUser(scope) {
      this.$confirm(`确认删除该条数据吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var obj = {
            userUid: scope.row.userUid
          }
          const loading = this.$loading({
            lock: true,
            text: '正在删除...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          delUser(obj).then((res) => {
            loading.close()
            if (res.flag == 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.fetchData()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    submit() {
      var roles = null
      if (this.roles) {
        roles = this.roles.join(',') //转字符串
      }
      var obj = {
        objectid: this.userId, //用户id
        roles: roles //角色id集合,以英文逗号隔开
      }
      const loading = this.$loading({
        lock: true,
        text: '正在提交...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      updateUserRole(obj).then((res) => {
        loading.close()
        if (res.code == 0) {
          this.dialogVisible = false
          this.$message({
            message: '提交成功',
            type: 'success'
          })
          this.fetchData()
        }
      })
    },
    getDep() {
      getOrgTreeSelect().then((res) => {
        if (res.code == 0) {
          this.treeData = res.dataList
          this.treeData.unshift({
            code: '',
            name: '全部'
          })
        }
      })
      getRoles().then((res) => {
        if (res.code == 0) {
          this.roleList = res.dataList
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
}

.tree-box {
  height: 600px;
  overflow-y: auto;
}

.user-unit-box {
  box-sizing: border-box;
  display: flex;
  justify-content: flex-start;
  flex-wrap: nowrap;

  .user-unit-box-left {
    width: 226px;
    margin-right: 10px;
  }

  .user-unit-box-right {
    width: calc(100% - 226px - 10px);
  }
}

.filter-container {
  display: flex;
  justify-content: flex-start;
}

.filter-item {
  width: 300px;
  margin-right: 10px;
}

.inputBox {
  text-align: left;
}

.el-table {
  ::v-deep {
    margin-top: 20px;

    .el-table__header {
      border-radius: 6px;
      overflow: hidden;
    }

    .el-table__cell {
      height: 50px;
      padding: 0;
    }

    .is-leaf {
      background-image: linear-gradient(to top, rgba(128, 191, 255, 1), rgba(51, 153, 255, 1));
      font-size: 14px;
      font-weight: 700;
      letter-spacing: 0px;
      line-height: 24px;
      color: rgba(255, 255, 255, 1);
      border-right: 1px solid white;
    }
  }
}

.fpjs {
  cursor: pointer;
  color: rgba(51, 153, 255, 1);
}

.operate_area {
  width: 180px;
  display: flex;
  justify-content: center;
  margin: 0 auto;

  img {
    cursor: pointer;
  }
}
</style>
